﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using SqlSugar;
using System;
using System.Linq.Expressions;
using System.Runtime.InteropServices;
using WebApi.Helpers;
using WebApi.Infrastructure;
using WebApi.Model;

namespace WebApi.Controllers
{
    /// <summary>
    /// 此控制器主要用于保存图片
    /// </summary>
    [Route("api/[controller]")]
    [ApiController]
    public class PictureController : ControllerBase
    {
        private readonly ILogger<PictureController> _logger;
        private readonly string savePath = AppSetting.GetValue("WebApiParams:PictureSavePath");

        public PictureController(ILogger<PictureController> logger)
        {
            _logger = logger;
        }

        /// <summary>
        /// 更新图片信息
        /// </summary>
        /// <param name="pic">图片model</param>
        /// <returns></returns>
        [HttpPost("AddPicture")]
        public PictureResult AddPicture(PictureModel pic)
        {
            var json = new PictureResult();
            try
            {
                if (string.IsNullOrEmpty(pic.RecordId))
                {
                    json.code = 400;
                    json.message = "RecordId为空";
                    return json;
                }
                var scale = "无秤号";
                if (pic.RecordId.Contains("#"))
                {
                    scale = pic.RecordId.Split('#')[0];
                }

                string picturePath = savePath + DateTime.Now.ToString("yyMMdd") + @"\Truck\" + @$"\{scale}\";
                string picName = pic.RecordId;

                pic.Pic1 = SavePicture(pic.Pic1, picturePath, $"{picName}_1.png")?.Replace(savePath, string.Empty)?.Replace(@"\", @"/");
                pic.Pic2 = SavePicture(pic.Pic2, picturePath, $"{picName}_2.png")?.Replace(savePath, string.Empty)?.Replace(@"\", @"/");
                pic.Pic3 = SavePicture(pic.Pic3, picturePath, $"{picName}_3.png")?.Replace(savePath, string.Empty)?.Replace(@"\", @"/");
                pic.Pic4 = SavePicture(pic.Pic4, picturePath, $"{picName}_4.png")?.Replace(savePath, string.Empty)?.Replace(@"\", @"/");

                pic.SecondPic1 = SavePicture(pic.SecondPic1, picturePath, $"{picName}_Second1.png")?.Replace(savePath, string.Empty)?.Replace(@"\", @"/");
                pic.SecondPic2 = SavePicture(pic.SecondPic2, picturePath, $"{picName}_Second2.png")?.Replace(savePath, string.Empty)?.Replace(@"\", @"/");
                pic.SecondPic3 = SavePicture(pic.SecondPic3, picturePath, $"{picName}_Second3.png")?.Replace(savePath, string.Empty)?.Replace(@"\", @"/");
                pic.SecondPic4 = SavePicture(pic.SecondPic4, picturePath, $"{picName}_Second4.png")?.Replace(savePath, string.Empty)?.Replace(@"\", @"/");

                pic.ScreenShot1 = SavePicture(pic.ScreenShot1, picturePath, $"{picName}_ScreenShot1.png")?.Replace(savePath, string.Empty)?.Replace(@"\", @"/");
                pic.ScreenShot2 = SavePicture(pic.ScreenShot2, picturePath, $"{picName}_ScreenShot2.png")?.Replace(savePath, string.Empty)?.Replace(@"\", @"/");


                using var conn = DbHelper.GetDbConn();
                var lastPic = conn.Queryable<PictureModel>().Where(it => it.RecordId == pic.RecordId).First();
                _logger.LogInformation($"查询到的已存在的图片信息:{JsonConvert.SerializeObject(lastPic)}");

                if (lastPic == null)
                {
                    _logger.LogInformation($"新增图片信息:{JsonConvert.SerializeObject(pic)}");
                    var insertAble = conn.Insertable(pic);
                    insertAble = insertAble.InsertColumns(it => new { it.RecordId, it.Pic1, it.Pic2, it.Pic3, it.Pic4, it.SecondPic1, it.SecondPic2, it.SecondPic3, it.SecondPic4, it.ScreenShot1, it.ScreenShot2 });
                    insertAble.ExecuteCommand();
                }
                else
                {
                    pic.Id = lastPic.Id;
                    _logger.LogInformation($"新更新的图片信息:{JsonConvert.SerializeObject(pic)}");
                    var updateAble = conn.Updateable<PictureModel>(pic);
                    updateAble = updateAble.UpdateColumns(it => new { it.SecondPic1, it.SecondPic2, it.SecondPic3, it.SecondPic4, it.ScreenShot2 });
                    updateAble.ExecuteCommand();
                }
                json.code = 200;
                json.message = "成功";
                json.data = null;
                return json;
            }
            catch (Exception e)
            {
                _logger.LogError(e, "保存图片出错");
                json.code = 400;
                json.message = "保存出错";
                return json;
            }
        }

        private string SavePicture(string base64, string path, string innerName)
        {
            return !string.IsNullOrEmpty(base64) ? FileHelper.SaveImageFromBase64(base64, path, innerName) : null;
        }

        /// <summary>
        /// 获取称重图片(铜粉车辆时传注册guid,其他车辆时传称重编号)
        /// </summary>
        /// <returns></returns>
        [HttpPost("GetImage")]
        public ReturnModel GetImage([FromForm] string recordId)
        {
            try
            {
                _logger.LogInformation($"{nameof(PictureController)}/{nameof(GetImage)}:{recordId}");
                ReturnModel returnModel = new ReturnModel();
                returnModel.Data = DbHelper.PictureModel.GetFirst(it => it.RecordId == recordId);
                returnModel.Count = returnModel.Data == null ? 0 : 1;
                return returnModel;
            }
            catch (Exception ex)
            {
                return _logger.ErrorModel(nameof(PictureController) + "-" + nameof(GetImage), ex);
            }
        }
    }
}
